package xyz.cfg

import java.io.{ Reader, BufferedReader }
import xyz.cfg.Cfg

object CfgFactory {
  //一行最多一个{,一个}，一个:,#注释必须单独一行
  def parseReader(reader: Reader): Cfg = {
    val res: Cfg = new Cfg
    val bufReader = new BufferedReader(reader)
    var lines: List[String] = List[String]()
    var line: String = bufReader.readLine
    while (null ne line) {
      val myline = line.trim
      if (myline.startsWith("#") || myline.length() == 0) {
        //skip
      } else {
        lines = lines.:+(myline)
      }
      line = bufReader.readLine
    }

    var startOne: Int = 0 //{
    var endOne: Int = 0 //}
    var pk: String = ""
    for (line <- lines) {
      val si: Int = line.indexOf("{")
      if (si >= 0) {
        startOne += 1
      }
      val ei = line.indexOf("}")
      if (ei >= 0) {
        endOne += 1
      }
      if (startOne > endOne) { //没有结束
        //判断是否有:
        val index: Int = line.indexOf(":")
        if (index > 0) {
          handle(index, res, line, pk)
        } else {
          if (si >= 0) {
            pk += line.replaceAll("\\{", "\\.")
          }
          if (ei >= 0) {
            if ("" == pk) {
              pk = ""
            } else {
              pk = pk.substring(0, pk.length() - 1)
              var lastIndex = pk.lastIndexOf(".")
              lastIndex match {
                case -1 => pk = ""
                case _ => pk = pk.substring(0, lastIndex + 1)
              }
            }
          }
        }
      } else { //结束一个
        //判断是否有:
        val index: Int = line.indexOf(":")
        if (index > 0) {
          handle(index, res, line, pk)
        }
        //最后恢复
        startOne = 0
        endOne = 0
        pk = ""
      }
    }
    res
  }

  private def handle(index: Int, res: Cfg, line: String, pk: String): Unit = {
    //还有可能key前面有
    var wkey: String = line.substring(0, index)
    wkey = wkey.replaceAll("\\{", "\\.")
    var wval: String = line.substring(index + 1)
    if (wval.endsWith("}")) {
      wval = wval.substring(0, wval.length - 1)
    }
    val rk: String = pk + wkey
    res.add(rk, wval)
  }

}